/**
 * Copyright (c) 2018-2024, NXOS Development Team
 * SPDX-License-Identifier: Apache-2.0
 * 
 * Contains: pipe
 * 
 * Change Logs:
 * Date           Author            Notes
 * 2024-11-09     JasonHu           Init
 */

#ifndef __XBOOK_PIPE__
#define __XBOOK_PIPE__

#include <nxos_mini.h>
#include <base/fifo.h>
#include <base/list.h>
#include <base/atomic.h>
#include <base/mutex.h>
#include <base/waitqueue.h>

#define NX_PIPE_SEND        0x01
#define NX_PIPE_RECV        0x02
#define NX_PIPE_NOWAIT      0x04

#define NX_PIPE_SIMPLEX     0x10
#define NX_PIPE_DUPLEX      0x20

#define NX_PIPE_ANONYMOUSE  0x40
#define NX_PIPE_NAMED       0x80

#define NX_PIPE_THREAD      0x100

#define NX_PIPE_SIZE_DEFAULT 0
#define NX_PIPE_SIZE_MAX    (32 * NX_MB)

#define NX_PIPE_NAME_LEN    32

struct NX_Pipe
{
    NX_List list; /* list on pipe system */
    char name[NX_PIPE_NAME_LEN];
    NX_Fifo *fifoMaster;
    NX_Fifo *fifoSlaver;
    NX_Atomic refernce; /* pipe ref */
    NX_Atomic masterRef; /* master pipe ref */
    NX_Atomic slaverRef; /* slaver pipe ref */
    NX_Atomic connectRef; /* slaver connect ref */
    NX_Size size;
    NX_U8 flags;
    NX_I32 masterTid; /* master thread id */
    NX_WaitQueue sendQueue;
    NX_WaitQueue recvQueue;
    NX_Mutex masterMutex;
    NX_Mutex slaverMutex;
};
typedef struct NX_Pipe NX_Pipe;

NX_Pipe *NX_PipeCreate(const char *name, NX_Size size, NX_U8 flags);
NX_Error NX_PipeDestroy(NX_Pipe *pipe);
NX_Error NX_PipeIncrease(NX_Pipe *pipe);
NX_Error NX_PipeDecrease(NX_Pipe *pipe);
NX_Error NX_PipeSend(NX_Pipe *pipe, void *buffer, NX_Size len, NX_Size *nsend);
NX_Error NX_PipeRecv(NX_Pipe *pipe, void *buffer, NX_Size len, NX_Size *nrecv);
NX_Pipe *NX_PipeConnectByName(const char *name);
NX_Pipe *NX_PipeConnectByPipe(NX_Pipe *pipe, NX_Bool isMaster);
NX_Error NX_PipeDisconnect(NX_Pipe *pipe);

NX_INLINE NX_Bool NX_PipeIsMaster(NX_Pipe *pipe)
{
    return (pipe->masterTid == NX_ThreadSelf()->tid);
}

#endif /* __XBOOK_PIPE__ */
